package com.hqully.smartfumehood.udp.handle;


import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
 * <p>
 *     UDPServer处理器，用于处理通过UDP端口传递的消息
 * </p>
 * @author liulingyu
 * @date 2022-05-12 17:47
 * @version 1.0
 */
@Slf4j
@Component
public class UDPServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {

        try {
            log.info("{}",msg);

            String strdata = msg.content().toString(CharsetUtil.UTF_8);
            //打印收到的消息
            log.info("---------------------receive data--------------------------");
            log.info(strdata);
            log.info("---------------------receive data--------------------------");


            //收到udp消息后，可通过此方式原路返回的方式返回消息，例如返回时间戳
            ctx.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("ok", CharsetUtil.UTF_8), msg.sender()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




}
